package org.myorg.v6;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;

import org.mortbay.log.Log;
import org.myorg.v4.FEvolution4;
import org.myorg.v4.FPeople4;
import org.myorg.v4.FPeopleWritable4;
import org.myorg.v4.Para4;

public class CMap2 extends Para4 {
	public void Island(FPeopleWritable4 value, int port) {

		String ID = "cn.edu.xmu";
		int mode = 0;
		int period = 10 * 1000;

		TransImpl tran = new TransImpl(ID, mode,imn,new InetSocketAddress("172.16.15.79", 36241),period);
		tran.start();

		FEvolution4 my_e = new FEvolution4(0.1, p_cross, p_mut);

		for (int j = 0; j < 100000; j++) {

			Log.info("loop " + j);

			ifc.caculate(value.getPersons());

			for (int i = 0; i < moving_rate; i++) {
				my_e.select(value);
				// my_e.select(best_people);
				my_e.crossOver(value);
				my_e.mutation(value);
				ifc.caculate(value.getPersons());

			}
			if ((1 - value.getBest().fitness) < 1.0E-6) {
				Log.info("end the program for achieve the best value " + value.getBest().fitness);
				break;
			}


			if (tran.isMaster()) {
				LinkedList<FPeopleWritable4> AllP = (LinkedList<FPeopleWritable4>) tran
				.Wait4AllData();

				// mycode

				Log.info("the number of people in AllP is" + AllP.size());

				FPeopleWritable4 res = new FPeopleWritable4();
				res.add((FPeople4)value);
				System.out.println("the number of people in res is" + res.p_num);

				for( Iterator itr = AllP.iterator();itr.hasNext();) {
					res.add((FPeople4) itr.next());
				}


				Arrays.sort(res.persons);

				FPeople4[] ap = res.seg(AllP.size()+1);
				FPeopleWritable4 np = new FPeopleWritable4(ap[ap.length - 1]);

				tran.send2All(np);
				//tran.send9(np);
				value = new FPeopleWritable4(np);

				Log.info("the number of people in master is" + np.p_num);
				Log.info("the number of people in value is" + value.p_num);
				Log.info("the best value in master is" + value.getBest().fitness);


			} else {
				try {
					tran.send(value);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Log.info("the data cann't be send out by slave");
					//e.printStackTrace();
				}
				//tran.send8(value);
				FPeopleWritable4 p = (FPeopleWritable4) tran.Wait4Data();
				if (p != null) {
					value = p;
				}
				

				Log.info("the best value in slave is" + value.getBest().fitness);

			}


		}
		
		tran.stop();
		
		// output.collect(NullWritable.get(), value);
	}

	public static void main(String[] args) {
		FPeopleWritable4 all_p = new FPeopleWritable4(ipn, igl);
		CMap2 m = new CMap2();
		m.Island(all_p, 8888);
	}
}


